# -*- coding: utf-8 -*-
from . import BaseController
from backend.libs import myjson as json
from backend.models import Banner


class List(BaseController):

    def get(self):
        c = Banner.objects
        name = self.get_argument('name', '')
        if name:
            c = c.filter(name__contains=name)
        state = self.int_argument('state', 0)
        c = c.filter(state=state)
        c = c.order_by('show_order')
        number_per_page = self.int_argument('pageSize', 50)
        paginator = self.pagination(c.all(), number_per_page=number_per_page)
        return self.render_json(data=paginator)


class BaseBannerController(BaseController):

    def set_banner_properties(self, banner, data):
        banner.state = data['state']
        banner.name = data['name']
        banner.show_order = data['show_order']
        banner.url = data.get('url', "")
        banner.save()
        return banner

class Update(BaseBannerController):

    def post(self):
        data = json.loads(self.request.body)
        url = data.get('url', '')
        if not url:
            return self.render_json(code=1001, msg='Banner的图片地址不能为空')
        banner_id = data['id']
        banner = Banner.objects.filter(id=banner_id).first()
        if not banner:
            return self.render_json(code=1001, msg='分类不存在')
        banner = self.set_banner_properties(banner, data)
        return self.render_json(data=banner.to_dict())


class Create(BaseBannerController):

    def post(self):
        data = json.loads(self.request.body)
        url = data.get('url', '')
        if not url:
            return self.render_json(code=1001, msg='Banner的图片地址不能为空')
        banner = Banner()
        banner = self.set_banner_properties(banner, data)
        return self.render_json(data=banner.to_dict())


class Delete(BaseController):

    def post(self, banner_id):
        banner_id = int(banner_id)
        if banner_id > 0:
            banner = Banner.objects.filter(id=banner_id).first()
            if banner:
                banner.state = 1
                banner.save()
        return self.render_json()

